package org.csu.mypetstore.persistence.impl;

import org.csu.mypetstore.domain.Sequence;
import org.csu.mypetstore.persistence.DBUtill;
import org.csu.mypetstore.persistence.SequenceDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


public class SequenceDAOImpl implements SequenceDAO {
    public static final String GET_SEQUENCE = "SELECT name, nextid FROM SEQUENCE WHERE NAME = ?";

    public static final String UPDATE_SEQUENCE = "UPDATE SEQUENCE SET NEXTID = ? WHERE NAME = ?";

    @Override
    public Sequence getSequence(Sequence sequence) {
        Sequence sequence_2 = null;

        try {
            Connection connection = DBUtill.getConnection();
            PreparedStatement pStatement = connection.prepareStatement(GET_SEQUENCE);
            pStatement.setString(1, sequence.getName());
            ResultSet resultSet = pStatement.executeQuery();
            if (resultSet.next()) {
                sequence_2 = new Sequence();
                sequence_2.setName(resultSet.getString(1));
                sequence_2.setNextId(resultSet.getInt(2));
            }
            DBUtill.closeConnection(connection);
            DBUtill.closePreparedStatement(pStatement);
            DBUtill.closeResultSet(resultSet);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sequence_2;
    }

    @Override
    public void updateSequence(Sequence sequence) {
        try {
            Connection connection = DBUtill.getConnection();
            PreparedStatement pStatement = connection.prepareStatement(UPDATE_SEQUENCE);
            pStatement.setInt(1, sequence.getNextId());
            pStatement.setString(2, sequence.getName());
            pStatement.executeUpdate();
            DBUtill.closePreparedStatement(pStatement);
            DBUtill.closeConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
